import {Button, Checkbox, Form, Input, message} from 'antd';
import {loginAction} from "@/store/user/actions";
import {useDispatch} from "react-redux";
import './index.less'
import {Login, LoginParam} from "@/api/user";
import {useNavigate} from "react-router-dom";
import {reactLocalStorage} from 'reactjs-localstorage';

const LoginPage = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch()  //拿到store中的dispatch函数，触发action

    const handleSubmit = (params: LoginParam) => {
        message.loading('登陆中').then(() => {
            Login(params).then((res: any) => {
                if (res.status === 200) {
                    // 将user信息存到缓存中
                    reactLocalStorage.setObject('user', res.result);
                    dispatch(loginAction(res.result));
                    message.destroy();
                    message.success('欢迎回来');
                    const urlParams = new URL(window.location.href).searchParams;
                    navigate(urlParams.get('redirect') || '/index') // 跳转到首页或重定向
                }
            })
        })
    };

    // 提交表单且数据验证成功后回调事件
    const onFinish = (values: any) => {
        handleSubmit(values)
    };

    // 提交表单且数据验证失败后回调事件
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <div className="container">
            <div className="form-content">
                <Form
                    name="basic"
                    labelCol={{span: 6}}
                    wrapperCol={{span: 16}}
                    style={{maxWidth: 500}}
                    initialValues={{remember: true}}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="Username"
                        name="username"
                        rules={[{required: true, message: 'Please input your username!'}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="Password"
                        name="password"
                        rules={[{required: true, message: 'Please input your password!'}]}
                    >
                        <Input.Password/>
                    </Form.Item>

                    <Form.Item name="remember" valuePropName="checked" wrapperCol={{offset: 8, span: 16}}>
                        <Checkbox>Remember me</Checkbox>
                    </Form.Item>

                    <Form.Item wrapperCol={{offset: 8, span: 16}}>
                        <Button type="primary" htmlType="submit">
                            Submit
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default LoginPage;
